package api;

import com.fasterxml.jackson.databind.ObjectMapper;
import common.Util;
import dao.Blog;
import dao.BlogDao;
import dao.User;
import dao.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 刘柄华
 * Date: 2022-06-21
 * Time: 16:46
 */

@WebServlet("/user")
public class UserServlet extends HttpServlet {
    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=utf-8");
        // 先检测当前是否登录. 如果未登录, 直接返回一个错误提示
        User user = Util.checkLoginStatus(req);
        if (user == null){
            String html = "您尚未登录";
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write(html);
            return;
        }

        String blogId = req.getParameter("blogId");
        if (blogId == null) {
            // 获取当前登录用户的信息
            String jsonString = objectMapper.writeValueAsString(user);
            resp.getWriter().write(jsonString);

        } else {
            // 获取指定文章的作者的信息
            // 根据 blogId 在数据库里查到对应的 userId , 再根据这个userId 拿到对应的 user 详情
            BlogDao blogDao = new BlogDao();
            Blog blog = blogDao.selectOne(Integer.parseInt(blogId));
            if (blog == null){
                String html = "<h3>指定的博客不存在 </h3>";
                resp.setContentType("text/html;charset=utf-8");
                resp.getWriter().write(html);
                return;
            }
            UserDao userDao = new UserDao();
            User author = userDao.selectById(blog.getUserId());
            // 在这个 author 返回之前, 把 isYourBlog 字段给设置进去
            author.setIsYourBlog(author.getUserId() == user.getUserId() ? 1 : 0);
            String jsonString = objectMapper.writeValueAsString(author);
            resp.getWriter().write(jsonString);
        }
    }
}
